package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.knowledge.base.pojo.CataloguePojo;
import com.xbongbong.pro.knowledge.base.pojo.OptionalRangePojo;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeBaseDetailDTO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeCatalogueListVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.KnowledgeCatalogueEntity;
import com.xbongbong.saas.domain.entity.KnowledgeDataEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.model.KnowledgeCatalogueModel;
import com.xbongbong.saas.model.KnowledgeDataModel;
import com.xbongbong.saas.service.KnowledgeBaseService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author mingliang
 * @Description 知识库帮助类
 * @Date 2022/7/18 11:23
 **/
@Component
public class KnowledgeBaseHelp {

    public static final Logger LOG = LoggerFactory.getLogger(KnowledgeBaseHelp.class);

    @Resource
    private KnowledgeBaseService knowledgeBaseService;
    @Resource
    private KnowledgeCatalogueModel knowledgeCatalogueModel;
    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private KnowledgeDataModel knowledgeDataModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private CompanyConfigModel companyConfigModel;





    /**
     * @Author mingliang
     * @Description 根据公司id，知识库id，登录用户获得所有可见的目录id
     * @Date 2022/7/18 13:40
     * @param corpid
     * @param knowledgeId
     * @param userVO
     **/
    public List<Long> getCatalogueIdList(String corpid, Long knowledgeId, UserVO userVO) throws XbbException {
        List<Long> catalogueIdList = new ArrayList<>();
        KnowledgeBaseDetailDTO knowledgeBaseDetailDTO = new KnowledgeBaseDetailDTO();
        knowledgeBaseDetailDTO.setCorpid(corpid);
        knowledgeBaseDetailDTO.setUserId(userVO.getUserId());
        knowledgeBaseDetailDTO.setLoginUser(userVO);
        knowledgeBaseDetailDTO.setId(knowledgeId);
        KnowledgeCatalogueListVO knowledgeCatalogueListVO = knowledgeBaseService.knowledgeCatalogueList(knowledgeBaseDetailDTO);
        List<CataloguePojo> catalogueList = knowledgeCatalogueListVO.getDepartmentTree();
        if (CollectionsUtil.isEmpty(catalogueList)){
            return catalogueIdList;
        }
        getCatalogueList(catalogueList,catalogueIdList);
        return catalogueIdList;
    }

    private void getCatalogueList(List<CataloguePojo> catalogueList, List<Long> resultCatalogueList) {
        if (CollectionsUtil.isEmpty(catalogueList)) {
            return;
        }
        for (CataloguePojo cataloguePojo : catalogueList) {
            resultCatalogueList.add(cataloguePojo.getValue());
            List<CataloguePojo> cataloguePojoList = cataloguePojo.getNodes();
            if (CollectionsUtil.isNotEmpty(cataloguePojoList)) {
                getCatalogueList(cataloguePojoList, resultCatalogueList);
            }
        }
    }


    /**
     * @param loginUser
     * @param managerConfig
     * @Author mingliang
     * @Description 判断用户知识条目是否拥有权限
     * @Date 2022/6/27 14:06
     **/
    public boolean permissionsValidation(UserVO loginUser, String managerConfig) throws XbbException {
        boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        Set<String> managerUserIdSet = new HashSet<>();
        if (StringUtil.isNotEmpty(managerConfig)) {
            List<OptionalRangePojo> optionalRangePojoList = JSONArray.parseArray(managerConfig, OptionalRangePojo.class);
            if (CollectionsUtil.isNotEmpty(optionalRangePojoList)) {
                optionalRangePojoList.forEach(e -> {
                    managerUserIdSet.add(e.getId());
                });
            }
        }
        return isAdminOrBoss || (CollectionsUtil.isNotEmpty(managerUserIdSet) && managerUserIdSet.contains(loginUser.getUserId()));
    }

    /**
     * @Author mingliang
     * @Description 移除掉html标签
     * @Date 2022/7/25 9:49
     * @param content
     **/
    public String cleanHtmlTag(String content) {
        return content.replaceAll("(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)", "");
    }

    /**
     * @Author mingliang
     * @Description 递归获得父目录下所有子目录,初始化时需要父目录id放进allCatalogueId里面
     * @Date 2022/8/19 10:09
     * @param corpid
     * @param knowledgeBaseId
     * @param allCatalogueId
     **/
    public void getAllChildCatalogueId(String corpid, Long knowledgeBaseId, List<Long> allCatalogueId) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("knowledgeBaseId", knowledgeBaseId);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.ORDER_BY, "parent_id asc");
        List<KnowledgeCatalogueEntity> catalogueEntityList = knowledgeCatalogueModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(catalogueEntityList)) {
            return;
        }
        for (KnowledgeCatalogueEntity knowledgeCatalogueEntity : catalogueEntityList) {
            if (allCatalogueId.contains(knowledgeCatalogueEntity.getParentId())){
                allCatalogueId.add(knowledgeCatalogueEntity.getId());
            }
        }
    }

    /**
     * 是否悬浮显示知识库
     * @param userVO
     * @return
     */
    public Boolean isShowKnowledgeBase(UserVO userVO) {
        if (Objects.isNull(userVO)) {
            return Boolean.FALSE;
        }
        UserConfigEntity userConfigEntity = userConfigModel.getByUserId(userVO.getUserId(), userVO.getCorpid(), UserConfigEnum.KNOWLEDGE_BASE_SHOW.getAlias());
        if (Objects.isNull(userConfigEntity)) {
            return Boolean.FALSE;
        }
        if (Objects.equals(userConfigEntity.getConfigValue(), "1") && userVO.getPermSet().contains(ProPermissionAliasEnum.KNOWLEDGE_BASE_VIEW.getAlias())) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * @Description: 根据公司id判断是否悬浮显示知识库
     * @param corpid
     * @Author cml
     * @CreateTime 2022/11/30 15:30
     */
    public Boolean isShowKnowledgeBase(String corpid) {
        // 如果求知识库显示出现异常，则直接不显示，不影响到客户使用
        if (StringUtil.isEmpty(corpid)) {
            return Boolean.FALSE;
        }
        try {
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ALIYUN_CALLCENTER_CONFIGURATION.getAlias(), corpid);
            if (Objects.isNull(companyConfigEntity) || StringUtil.isEmpty(companyConfigEntity.getConfigValue())) {
                return Boolean.FALSE;
            }
            String configValue = companyConfigEntity.getConfigValue();
            JSONObject configValueObject = JSON.parseObject(configValue);
            JSONArray seatsWorkbench = configValueObject.getJSONArray("seatsWorkbench");
            if (CollectionsUtil.isEmpty(seatsWorkbench)) {
                return Boolean.FALSE;
            }
            for (int i = 0; i < seatsWorkbench.size(); i++) {
                JSONObject jsonObject = seatsWorkbench.getJSONObject(i);
                String config = jsonObject.getString("config");
                Integer value = jsonObject.getInteger("value");
                if (Objects.equals(config, "selectTheSkillGroupToKnowledgeBaseShow") && Objects.equals(1, value)) {
                    return Boolean.TRUE;
                }
            }
            return Boolean.FALSE;
        } catch (Exception exception) {
            LOG.error("获取悬浮显示云呼按钮标识发现未知异常corpid:{},异常信息：{}", corpid, exception);
            return Boolean.FALSE;
        }
    }


    /**
     * 根据公司id，知识库id删除所有知识条目
     * @param corpid
     * @param knowledgeBaseId
     * @throws XbbException
     */
    public void deleteKnowledgeBaseByKnowledgeBaseId(String corpid, Long knowledgeBaseId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.COLUMNS, "id");
        param.put(StringConstant.CORPID, corpid);
        param.put("knowledgeBaseId", knowledgeBaseId);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<KnowledgeDataEntity> entitys = knowledgeDataModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)) {
            List<Long> idList = entitys.stream().map(e -> e.getId()).collect(Collectors.toList());
            knowledgeDataModel.deleteByCorpIdKnowledgeId(corpid, idList);
            paasEsModel.deleteBatch(idList, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        }
    }

    /**
     * 根据dataId删除知识条目
     * @param corpid
     * @param dataIdList
     * @throws XbbException
     */
    public void deleteKnowledgeBaseByDataId(String corpid, List<Long> dataIdList) throws XbbException {
        if (CollectionsUtil.isNotEmpty(dataIdList) && StringUtil.isNotEmpty(corpid)) {
            knowledgeDataModel.deleteByCorpIdKnowledgeId(corpid, dataIdList);
            paasEsModel.deleteBatch(dataIdList, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        }
    }
}
